

#include <pic.h>
#include <io.h>
#include <debug.h>

dword g_irqbase;

/**
 * Initialize PIC hardware (8259)
 */
int init_pic(void)
{
	int ret = 0;
	
	pic_remap(0x20);
	pic_disable();
	
	return ret;
}

/**
 * Remap the IRQs generated to a new IDT range
 * 
 * byte newint - new IDT base interrupt
 *   ! should be >31 to avoid x86 exceptions/traps/faults
 * 
 * ! device manager code relies on this to handle device interrupts
 */
void pic_remap(byte newint)
{
	outb(PIC_MASTER_CMD, PIC_ICW1);
	outb(PIC_SLAVE_CMD, PIC_ICW1);
	
	outb(PIC_MASTER_DATA, newint);
	outb(PIC_SLAVE_DATA, newint+8);
	
	outb(PIC_MASTER_DATA, 0x04);
	outb(PIC_SLAVE_DATA, 0x02);
	
    outb(PIC_MASTER_DATA, PIC_ICW4);
    outb(PIC_SLAVE_DATA, PIC_ICW4);
    
    // needed?
	//outb(0x21, 0x0);
    //outb(0xA1, 0x0);
    
    g_irqbase = newint;
    
	debugf("[PIC] IRQs Remapped to 0x%x-0x%0x\n", newint, newint+15);
}

/**
 * Mask all PIC interrupts
 */
void pic_disable(void)
{
	outb(PIC_MASTER_DATA, 0xFF);
	outb(PIC_SLAVE_DATA, 0xFF);
}

/**
 * Unmask all PIC interrupts
 */
void pic_enable(void)
{
	outb(PIC_MASTER_DATA, 0x00);
	outb(PIC_SLAVE_DATA, 0x00);
}
